package com.lambkit.devops;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.lambkit.core.json.Json;
import com.lambkit.db.DbPool;
import com.lambkit.db.IDb;
import com.lambkit.db.IRowData;
import com.lambkit.db.RowData;
import com.lambkit.devops.monitor.MonitorTask;

import java.util.Map;

/**
 * 监控任务
 * 
 * @author DELL
 *
 */
public class DevopsMonitorTask implements Runnable {

	private MonitorTask monitorTask = new MonitorTask();

	@Override
	public void run() {
		// TODO Auto-generated method stub
		String value = DevopsKit.getSetting("lambkit.devops.monitortask");
		if (!"true".equals(value)) {
			return;
		}
		Map<String, Object> result = monitorTask.excute(true);
		if (result == null) {
			return;
		}

		// 上报父节点
		String name = DevopsKit.getSetting("lambkit.devops.parent.name");
		String url = DevopsKit.getSetting("lambkit.devops.parent.url");
		if (StrUtil.isNotBlank(url)) {
			Map<String, String> headerMap = DevopsKit.header();
			HttpResponse res = HttpRequest.post(url).headerMap(headerMap, true).body(Json.use().toJson(result)).execute();
			String devopsLog = DevopsKit.getConfig("lambkit.devops.logname");
			if (StrUtil.isNotBlank(devopsLog)) {
				IDb db = DbPool.use(devopsLog);
				RowData record = db.newRowData();
				record.set("url", url);
				record.set("name", name);
				record.set("content", "monitor");
				record.set("result", res.body());
				record.set("status", res.getStatus());
				record.set("created", DateUtil.now());
				record.setTableName("devops_post_record");
				record.setPrimaryKey("post_record_id");
				db.save(record);
			}
		}
	}

}
